package com.example.black.myapplication.shader;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Matrix;
import android.graphics.Shader;
import android.support.annotation.Nullable;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.util.Log;

/**
 * <pre>
 *     author : 28476
 *     e-mail : hao.wang@1hai.cn
 *     time   : 2019/01/02/17:31
 *     desc   :
 *     version: 1.0
 * </pre>
 */

public class LinearGradientTextView extends android.support.v7.widget.AppCompatTextView {

    public static final String TAG = LinearGradientTextView.class.getSimpleName();
    private TextPaint paint;
    private LinearGradient linearGradient;
    private int[] colors = {Color.RED,Color.GREEN,Color.BLUE};
    private int [] colors1 =  new int[]{0x22ffffff,0xffffffff,0x22ffffff};
    private float measureWidth;
    private Matrix matrix;
    private int translateX;
    private float deltaX = 20;
    public LinearGradientTextView(Context context) {
        super(context);
        initConfig();
    }

    public LinearGradientTextView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        initConfig();
    }

    public LinearGradientTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initConfig();
    }

    private void initConfig() {
        paint = getPaint();
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        String text = getText().toString();
        measureWidth = paint.measureText(text);
        if (measureWidth > w){
            measureWidth = w;
        }
        int gradientSize = (int) (9 * measureWidth/text.length());//控制渐变几个字的长度
        //控制线性渲染器角度
        linearGradient = new LinearGradient(gradientSize, 0, 0, 0, colors1, new float[]{0,0.5f , 1}, Shader.TileMode.CLAMP);
        paint.setShader(linearGradient);
        matrix = new Matrix();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        translateX += deltaX;
        Log.d(TAG, "onDraw: before deltaX："+deltaX);
        if (translateX > measureWidth + 1 || translateX < 1){
            deltaX = - deltaX;//一旦到边界，取相反数
            Log.d(TAG, "onDraw: after deltaX："+deltaX);
        }
        matrix.setTranslate(translateX,0);
        linearGradient.setLocalMatrix(matrix);//矩阵控制大小
        postInvalidateDelayed(100);
    }


}
